﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Web.Services;

namespace Geosearch
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                List<string> info = new List<string>();

                XDocument doc = XDocument.Load(Server.MapPath("~/Geonames.xml"));
                var res = from x in doc.XPathSelectElements("/geonames/country")
                          where (string)x.Element("countryName") == search.Value
                           select x;


                foreach (var record in res)
                {
                    string s = "name: "+record.Element("countryName").Value;
                    s += "<br />population: "+record.Element("population").Value;
                    s += "<br />capital: " + record.Element("capital").Value;
                    s += "<br />continent: " + record.Element("continentName").Value;
                    uiTestPanel.Controls.Add(new LiteralControl("<p>" + s + "</p>"));
                }
            }
        }
        /*
    <country>
        <countryCode>AD</countryCode>
        <countryName>Andorra</countryName>
        <isoNumeric>020</isoNumeric>
        <isoAlpha3>AND</isoAlpha3>
        <fipsCode>AN</fipsCode>
        <continent>EU</continent>
        <continentName>Europe</continentName>
        <capital>Andorra la Vella</capital>
        <areaInSqKm>468.0</areaInSqKm>
        <population>84000</population>
        <currencyCode>EUR</currencyCode>
        <languages>ca</languages>
        <geonameId>3041565</geonameId>
        <bBoxWest>1.4071867141112762</bBoxWest>
        <bBoxNorth>42.65604389629997</bBoxNorth>
        <bBoxEast>1.7865427778319827</bBoxEast>
        <bBoxSouth>42.42849259876837</bBoxSouth>
    </country>
         */
        //static Dictionary<string, string> Contry = new Dictionary<string, string>();

        [WebMethod]
        public static List<string> GetCountryNames(string input, int limit)
        {
            //System.Web.HttpContext.Current.Server.MapPath();
            XDocument doc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Geonames.xml"));
            var res = (from x in doc.XPathSelectElements("/geonames/country/countryName")
                      where x.Value.StartsWith(input, true, null)
                       select x.Value).Take(limit);
            return res.ToList<string>();
        }
    }
}